package cn.zn.controller.system;

import cn.zn.base.bean.dto.ResultData;
import cn.zn.base.common.utils.ResultUtil;
import cn.zn.framework.service.SysLoginService;
import cn.zn.framework.utils.SecurityUtil;
import cn.zn.menu.entity.SysMenu;
import cn.zn.user.entity.SysUser;
import cn.zn.menu.service.SysMenuService;
import cn.zn.role.service.SysRoleService;
import cn.zn.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author zn-admin
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysMenuService menuService;

    /**
     * 登录方法
     *
     * @param vo 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResultData login(@RequestBody LoginVo vo) {
        // 生成令牌
        Map<String, String> tokenMap = loginService.login(vo.getUsername(), vo.getPassword());
        return ResultUtil.success(tokenMap);
    }

    /**
     * 登录方法
     *
     * @param vo 登录信息
     * @return 结果
     */
    @GetMapping("/getToken")
    public ResultData getToken(LoginVo vo) {
        // 生成令牌
        Map<String, String> tokenMap = loginService.login(vo.getUsername(), vo.getPassword());
        return ResultUtil.success(tokenMap);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/userInfo")
    public ResultData getUserInfo() {
        SysUser sysUser = SecurityUtil.getTheUser();
        // 角色集合
        Set<String> roles = roleService.selectRolePermissionByUserId(sysUser.getId(), sysUser.getLoginName());
        // 权限集合
        Set<String> permissions = menuService.selectMenuPermsByUserId(sysUser.getId(), sysUser.getLoginName());
        Map<String, Object> result = new HashMap<>();
        result.put("user", sysUser);
        result.put("roles", roles);
        result.put("permissions", permissions);
        return ResultUtil.success(result);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public ResultData getRouters(@RequestParam(value = "systemNames", required = false) String[] systemNames) {
        // 用户信息
        SysUser user = SecurityUtil.getTheUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getId(), user.getLoginName(), systemNames);
        return ResultUtil.success(menuService.buildMenus(menus));
    }

    /**
     * 登录方法
     *
     * @param vo 登录信息
     * @return 结果
     */
    @PostMapping("/ssoLogin")
    public ResultData ssoLogin(@RequestBody LoginVo vo) {
        // 生成令牌
        Map<String, String> tokenMap = loginService.ssoLogin(vo.getSsoToken());
        return ResultUtil.success(tokenMap);
    }
}
